let https = require('https')
let qs = require('querystring')
let express = require('express')
let app = express()
let fs = require('fs')
let bodyParser = require('body-parser')

let access_token = ''
let access_token1 = ''

const param = qs.stringify({
	'grant_type': 'client_credentials',
	'client_id': 'TCs9N88mgNyBEOGhKGsWgzo3',
	'client_secret': 'tSgDmFCx5HGGH8oXixTEWA1bhRV7TfYB'
})

let bitmap = fs.readFileSync('./public/images/my03.png')
let base64str1 = new Buffer(bitmap).toString('base64')

app.use(bodyParser.urlencoded({
	limit: '50mb',
	extended: true
}))

app.use(express.static('./public'))

app.post('/access', function(req, res) {
	https.get({
			hostname: 'aip.baidubce.com',
			path: '/oauth/2.0/token?' + param,
			agent: false
		},
		function(res) {
			res.setEncoding('utf8')
			res.on('data', function(data) {
				access_token = JSON.parse(data).access_token
			})
		}
	)
})
app.post('/access1', function(req, res) {
	https.get({
			hostname: 'aip.baidubce.com',
			path: '/oauth/2.0/token?' + param,
			agent: false
		},
		function(res) {
			res.setEncoding('utf8')
			res.on('data', function(data) {
				access_token1 = JSON.parse(data).access_token
			})
		}
	)
})
app.post('/judge', function(req, res) {
	let options = {
		host: 'aip.baidubce.com',
		path: '/rest/2.0/face/v3/search?access_token="' + access_token + '"',
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		}
	}
	let contents = JSON.stringify({
		image: req.body.img.replace(/\s/g, "+").replace(/^data:image\/\w+\Wbase64,/, ""),
		image_type: "BASE64",
		group_id_list: "test"
	})

	let req_baidu = https.request(options, function(res_baidu) {
		res_baidu.setEncoding('utf8')
		res_baidu.on('data', function(chunk) {
			res.send(chunk)
		})

	})
	req_baidu.write(contents)
	req_baidu.end()

})

app.post('/adduser', function(req, res) {
	let options = {
		host: 'aip.baidubce.com',
		path: '/rest/2.0/face/v3/faceset/user/add?access_token="' + access_token1 + '"',
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		}
	}
	console.log(JSON.parse(req.body.data));
	let contents = JSON.stringify({
		image: JSON.parse(req.body.data).dataurl.replace(/\s/g, "+").replace(
			/^data:image\/\w+\Wbase64,/, ""),
		image_type: "BASE64",
		group_id: "test",
		user_id: JSON.parse(req.body.data).userid
	})

	let req_baidu = https.request(options, function(res_baidu) {
		res_baidu.setEncoding('utf8')
		res_baidu.on('data', function(chunk) {
			res.send(chunk)
		})

	})
	req_baidu.write(contents)
	req_baidu.end()

})
let server = app.listen(3302, function() {
	console.log('listening at http://%s', 'localhost:3302');
})
